/**
 * XGPHP 轻量级PHP框架
 * @link http://xgphp.xg3.cn
 * @version 1.2.0
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @author 讯高科技 <xungaokeji@qq.com>
*/
(function(){
window.$=window.jQuery=window.jQuery||window?.layui?.$;
if(!window.$){
	return;
}
window.xg={};
xg.def=function(mod,callback){
	if(xg.isfun(callback)){
		xg[mod]=callback();
	}else{
		xg[mod]=callback;
	}
}
xg.loadjs=function(url,callback){
	if(!xg.isfun(callback)){
		callback=function(){};
	}
	xg.jsloaded = xg.jsloaded||[];
	if(xg.jsloaded.indexOf(url)>-1){
		return callback(2);
	}
	if($('script[src^="'+url+'"]').length)return;
	var timer=setInterval(function(){
		var loaded=xg.jsloaded.indexOf(url)>-1;
		i++;
		if(loaded){
			clearInterval(timer);
			callback(2);
			return;
		}
		if(i>100){
			document.head.removeChild(elem);
			clearInterval(timer);
			callback(0);
		}
	},50);
	var elem=document.createElement('script');
	elem.src=url;
	elem.async=true;
	elem.onload=function(){xg.jsloaded.push(url);clearInterval(timer);callback(1);}
	elem.onerror=function(e){xg.jsloaded.push(url);clearInterval(timer);}
	var i=0;
	document.head.appendChild(elem);
}
xg.mod=function(mod,callback){
	xg.modleuLoadedCallbacks=xg.modleuLoadedCallbacks||{};
	xg.modleuLoadedCallbacks[mod]=xg.modleuLoadedCallbacks[mod]||[];
	if(!xg[mod]){
		if(xg.isfun(callback)){
			xg.modleuLoadedCallbacks[mod].push(callback);
		}
		var curjs=document.currentScript.src||'/static/xg/xg.js';
		var dir=curjs.substring(0,curjs.lastIndexOf('/')+1);
		xg.loadjs(dir+'modules/'+mod+'.js',function(){
			for(let i in xg.modleuLoadedCallbacks[mod]){
				xg.modleuLoadedCallbacks[mod][i]();
			}
			xg.modleuLoadedCallbacks[mod]=[];
		});
	}else{
		callback(2);
	}
}
xg.iswin=function(v){return v&&(v.window===v);}
xg.isstr=function(v){return xg.type(v)=='string';}
xg.isobj=function(v){return xg.type(v)=='object';}
xg.iseobj=function(v){if(xg.isobj(v)){for(var i in v){return false;}return true;}return false;}
xg.isarr=function(v){return xg.type(v)=='array';}
xg.isfun=function(v){return xg.type(v)=='function';}
xg.isnum=function(v){return xg.type(v)=='number';}
xg.isnan=function(v){return isNaN(v);}
xg.isbool=function(v){return xg.type(v)=='boolean';}
xg.istrue=function(v){return v===1||v==='1'||v===true;}
xg.isfalse=function(v){return v===0||v==='0'||v===false;}
xg.isunde=function(v){return xg.type(v)=='undefined';}
xg.isnull=function(v){return v===null;}
xg.isfile=function(v){return xg.type(v)=='file';}
xg.isset=function(v){return xg.type(v)!=='undefined' && xg.type(v)!=='null';}
if(typeof HTMLElement === 'object'){
	xg.isnode=function(v){return v instanceof HTMLElement;}
}else{
	xg.isnode=function(v){return xg.isobj(v) && v.nodeType === 1 && xg.isstr(v.nodeName);}
}
xg.isjq=function(v){return v instanceof jQuery;}

xg.type=function(v){
	if(v===null)return 'null';
	if(v instanceof window.File)return 'file';
	if(v instanceof window.Blob)return 'blob';
	var type=typeof(v);
	if(type=='object')return((Array.isArray||function(v){return Object.prototype.toString.call(v)==='[object Array]';})(v)?'array':'object');
	return type;
};
xg.obj2arr=function(v){var r=[];for(var i in v){r.push(v[i]);}return r;};

xg.div=function(c){return $('<div/>').addClass(c||'').appendTo('body');};
xg.li=function(c){return $('<li/>').addClass(c||'').appendTo('body');};
xg.ul=function(c){return $('<ul/>').addClass(c||'').appendTo('body');};

xg.int=function(n){
	n=n.replace(/[^0-9\-]/g,'')
	return xg.isnan(n)?0:parseInt(n);
}
xg.float=function(n){
	n=n.replace(/[^0-9\.\-]/g,'');
	return xg.isnan(n)?0:parseFloat(n);
}

xg.zero=function(n){
	if(n<10)return '0'+n;
	return n;
}
xg.time=function(){
	return new Date().getTime();
}
xg.date=function(type){
	var arr=[];
	arr.push(xg.zero(new Date().getFullYear()));
	arr.push(xg.zero(new Date().getMonth()+1));
	arr.push(xg.zero(new Date().getDate()));
	arr.push(xg.zero(new Date().getHours()));
	arr.push(xg.zero(new Date().getMinutes()));
	arr.push(xg.zero(new Date().getSeconds()));
	if(type==0){
		return arr[0]+'-'+arr[1]+'-'+arr[2]+' '+arr[3]+':'+arr[4]+':'+arr[5];
	}else if(type==1){
		return arr[0]+'-'+arr[1]+'-'+arr[2];
	}else if(type==2){
		return arr[3]+':'+arr[4]+':'+arr[5];
	}
	return arr;
}

xg.storage=function(key,value){
	if(xg.isunde(value)){
		return JSON.parse(localStorage.getItem(key));
	}
	if(xg.isnull(value)){
		return localStorage.removeItem(key);
	}
	return localStorage.setItem(key,JSON.stringify(value));
}

xg.randstr=function(l,t){
	var i,e,b='abcdefghijklmnopqrstuvwxyz',c='',l=l||10;
	if(xg.isnum(t)){
		if(t==0)b='123456789';
		if(t>0)b+='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		if(t>1)b+='0123456789';
	}
	for(i=0;i<l;i++){
		c+=b.charAt(Math.floor(Math.random()*b.length));
	}
	return c;
}

xg.hook={
	data:{},
	onceList:[],
	reg(name,key,fun,once){
		if(xg.isfun(key)){
			fun=key;
			key=name;
		}
		if(!xg.isobj(xg.hook.data[name])){
			xg.hook.data[name]={};
		}
		xg.hook.data[name][key]=fun;
		function unreg(){
			xg.hook.unreg(name,key);
		};
		unreg.unreg=unreg;
		if(once){
			xg.hook.onceList.push(fun);
		}
		return unreg;
	},
	once(name,key,fun){
		return xg.hook.reg(name,key,fun,true);
	},
	unreg(name,key){
		if(xg.hook.data[name]&&xg.hook.data[name][key]){
			delete xg.hook.data[name][key];
		}
	},
	run(name){
		if(!xg.isobj(xg.hook.data[name])){
			xg.hook.data[name]={};
		}
		const hooks=xg.hook.data[name];
		const results={};
		const args=[];
		for(let i=1;i<arguments.length;i++){
			args.push(arguments[i]);
		}
		let prevResult=null;
		const controls={
			hooks,
			allResults(){
				return xg.obj2arr(results);
			},
			resultsMap(){
				return results;
			},
			prevResult(){
				return prevResult;
			}
		};
		for(let key in hooks){
			const fun=hooks[key];
			if(xg.isfun(fun)){
				const onceIndex=xg.hook.onceList.indexOf(fun);
				if(onceIndex>-1){
					xg.hook.unreg(name,key);
					xg.hook.onceList.splice(onceIndex,1);
				}
				const result=fun.apply(controls,args);
				if(!xg.isunde(result)){
					results[key]=result;
					prevResult=result;
				}
			}
		}
		return xg.obj2arr(results);
	}
};

xg.ajax=function(){
	let url='',type='get',data={},dataType='json';
	for(let i in arguments){
		const arg=arguments[i];
		if(arg instanceof jQuery || xg.isnode(arg)){
			const $dom=$(arg);
			if($dom.is('form')){
				if($dom.attr("action")){
					url=$dom.attr("action");
				}
				if($dom.attr("method")=='get' || $dom.attr("method")=='post'){
					type=$dom.attr("method");
				}
				data=$dom.serializeArray();
			}
		}else if(xg.isstr(arg)){
			if(arg=='get' || arg=='post'){
				type = arg;
			}else if(arg=='json' || arg=='html' || arg=='jsonp' || arg=='text' || arg=='xml'){
				dataType = arg;
			}else{
				url = arg;
			}
		}else if(xg.isobj(arg)){
			data=Object.assign(data,arg);
		}
	}
	if(data){
		data=xg.trim(data);
	}
	return new Promise(function(resolve,reject){
		const options={
			url,
			type,
			data,
			dataType,
			success:function(data){
				resolve(data);
			},
			error:function(xhr, status, error){
				reject(xhr, status, error);
			}
		}
		jQuery.ajax(options);
	});
};
xg.trim=function(data){
	if(xg.isobj(data)){
		const newData={};
		for(let key in data){
			newData[xg.trim(key)]=xg.trim(data[key]);
		}
		return newData;
	}else if(xg.isarr(data)){
		const newData=[];
		for(let i in data){
			newData.push(xg.trim(data[i]));
		}
		return newData;
	}else if(xg.isstr(data)){
		return data.replace(/(^\s*)|(\s*$)/g, "");
	}else{
		return data;
	}
};
xg.concat=function(){
	let result=xg.isarr(this)?this:[];
	for(let i in arguments){
		const array=arguments[i];
		if(xg.isarr(array) && this!==array && array.length){
			for(let item of array){
				result.push(item);
			}
		}
	}
	return result;
};
xg.get=function(){
	const args = Array.prototype.slice.call(arguments);
	args.push('get');
	return xg.ajax.apply(this,args);
};
xg.post=function(){
	const args = Array.prototype.slice.call(arguments);
	args.push('post');
	return xg.ajax.apply(this,args);
};
xg.url=function(u,p){
	var m,c,a;
	var pa={};
	var xginfo=window.xginfo||{};
	var root=xginfo.root||'/';
	var route=xginfo.route||false;
	if(xg.isnull(u)||xg.isunde(u)){
		u=location.href.toString();
	}else if(xg.isobj(u)&&!u.isxgurl){
		var p=u;
		var u='';
	}
	if(u=='/')return root;
	if(u.indexOf('/')===0)u=u.substr(1);
	if(u.indexOf('?')>-1){
		var ua1=u.split('?');
		u=ua1[0];
		var qps=ua1[1].split('&');
		for(var i in qps){
			var qps2=qps[i].split('=');
			pa[qps2[0]]=qps2[1];
		}
	}
	var ua2=u.split('/');
	if(ua2.length==3){
		m=ua2[0];
		c=ua2[1];
		a=ua2[2];
	}else if(ua2.length==2){
		c=ua2[0];
		a=ua2[1];
	}else if(ua2.length==1){
		a=ua2[0];
	}
	if(xg.isstr(p)){
		if(p.substr(0,1)=='?')p=p.substr(1);
		ps=p.split('&');
		for(var i in ps){
			var ps2=ps[i].split('=');
			pa[ps2[0]]=ps2[1];
		}
	}else if(xg.isobj(p)){
		for(var i in p){
			pa[i]=p[i];
		}
	}
	var pa1=[];
	for(var i in pa){
		pa1.push(i+'='+pa[i]);
	}
	p=pa1.join('&');
	var get=getparams();
	if(!m)m=xginfo.app||'';
	if(!c)c=xginfo.controller||'';
	if(!a)a=xginfo.action||'';
	var pa2=[];
	if(p)pa2.push(p);
	if(root.substr(-1)!=='/'){
		root+='/';
	}
	if(route){
		var rt=root+m+'/'+c+'/'+a+'.html'+(pa2.length>0?('?'+pa2.join('&')):'');
	}else{
		var rt=root+'index.php?app='+m+'&module='+c+'&action='+a+'&'+pa2.join('&');
	}
	return rt;
	function getparams(){
		var a=document.createElement('a');
		a.href=location;
		var ret={},
			seg=a.search.replace(/^\?/,'').split('&'),
			len=seg.length,i=0,s;
		for(;i<len;i++){
			if(!seg[i]){continue;}
			s=seg[i].split('=');
			ret[s[0]]=s[1];
		}
		return ret;
	}
}
})();